import json
import os
from mcp.server.fastmcp import FastMCP
# 加载配置文件
config_path = os.path.join(os.path.dirname(__file__), 'mcp.config.json')

with open(config_path, 'r', encoding='utf-8') as f:
    config = json.load(f)

# 创建MCP服务器并应用配置
mcp = FastMCP(
    name="Math Operations Server",
    servers=config['mcpServers'],
    max_threads=int(config['mcpServers']['math-service']['env'].get('MATH_PRECISION', '2')),
       request_timeout=30
)

@mcp.tool()
def add_numbers(a: float, b: float) -> float:
    """加法运算"""
    return a + b

@mcp.tool()
def subtract_numbers(a: float, b: float) -> float:
    """减法运算"""
    return a - b

@mcp.tool()
def multiply_numbers(a: float, b: float) -> float:
    """乘法运算"""
    return a * b

@mcp.tool()
def divide_numbers(a: float, b: float) -> str:
    """除法运算"""
    try:
        if b == 0:
            return "错误: 除数不能为零"
        return f"{a / b:.2f}"
    except Exception as e:
        return f"计算错误: {str(e)}"

@mcp.tool()
def square_number(x: float) -> float:
    """平方运算"""
    return x ** 2

@mcp.tool()
def sqrt_number(x: float) -> str:
    """平方根运算"""
    try:
        if x < 0:
            return "错误: 负数不能开平方"
        return f"{x ** 0.5:.2f}"
    except Exception as e:
        return f"计算错误: {str(e)}"

@mcp.resource("greeting://{name}")
def get_greeting_resource(name: str) -> str:
    """Get a greeting resource for the specified name"""
    return f"Greetings resource for {name}: Hello and welcome!"


if __name__ == "__main__":
    mcp.run(transport="stdio")